package com.lizx.framework.web.smart.framework.core.helper;

import com.lizx.framework.web.smart.framework.core.annotations.SmartController;
import com.lizx.framework.web.smart.framework.core.annotations.SmartRequest;
import com.lizx.framework.web.smart.framework.core.wrapper.HandlerWrapper;
import com.lizx.framework.web.smart.framework.core.wrapper.RequestWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * controller容器
 * @Author: lizx
 * @Description:
 * @Date: Create in 2019/1/18 11:11 AM
 */
public class SmartControllerHelper {
    /**
     * 请求与处理器的映射关系
     */
    private static final Map<RequestWrapper,HandlerWrapper> METHOD_MAP = new HashMap<>();

    static {
        //获取所有的controller类
        Set<Class<?>> controllerClassSet = SmartClassHelper.getControllerClassSet();
        if (CollectionUtils.isNotEmpty(controllerClassSet)) {
            for (Class<?> controllerClass : controllerClassSet) {
                //获取当前controller类的所有方法
                Method[] methods = controllerClass.getMethods();
                if (ArrayUtils.isNotEmpty(methods)) {
                    for (Method method : methods) {
                        //如果当前方法有request注解
                        if (method.isAnnotationPresent(SmartRequest.class)) {
                            SmartRequest request = method.getAnnotation(SmartRequest.class);
                            String mapping = request.value();
                            if (mapping.matches("\\w+:/\\w*")) {
                                //解析请求,封装映射对象
                                String[] array = mapping.split(":");
                                if (ArrayUtils.isNotEmpty(array) && array.length == 2) {
                                    String requestMethod = array[0];
                                    String requestPath = array[1];
                                    RequestWrapper requestWrapper = new RequestWrapper(requestMethod,requestPath);
                                    HandlerWrapper handlerWrapper = new HandlerWrapper(controllerClass,method);
                                    METHOD_MAP.put(requestWrapper, handlerWrapper);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取指定handler
     * @param requestMethod
     * @param requestPath
     * @return
     */
    public static HandlerWrapper getHandlerWrapper(String requestMethod,String requestPath){
        RequestWrapper requestWrapper = new RequestWrapper(requestMethod,requestPath);
        return METHOD_MAP.get(requestWrapper);
    }
}
